package com.etnoe.gis.service;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author: 蒋学伟
 * @create: 2020-06-16 14:47:34
 * @Description 文件管理
 */
@Service
@Log4j2
public class FileUploadService {

    /***
     * 重载文件下载，供项目文件使用
     * @param response
     * @param fileName
     */
    public void getFile(InputStream inputStream, HttpServletResponse response, String fileName) {
        String extension = FilenameUtils.getExtension(fileName).toLowerCase();
        if (extension.equals("jpg") || extension.equals("jpeg")) {
            response.setContentType("image/jpeg");
        } else if (extension.equals("png")) {
            response.setContentType("image/png");
        } else if (extension.equals("gif")) {
            response.setContentType("image/gif");
        } else {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
        }
        try {
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);

        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(inputStream);
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
